package com.hxkcloud.patient;

import android.app.Activity;
import android.util.Log;

import com.hxkcloud.patient.config.ApplicationConfig;

import java.util.Stack;

/**Log
 * Created by william_sun on 2016-07-05.
 * Description:
 */
public class ActivityManager {

    private static final String TAG = "ActivityManager";
    private static boolean debug = ApplicationConfig.IS_DEBUG;
    private static ActivityManager mActivityManager;
    private static Stack<Activity> activityStack = new Stack<Activity>();

    private ActivityManager() {

    }

    /**
     * 创建单实例，提供静态方法供调用
     */
    public static ActivityManager getInstance() {
        if (mActivityManager == null) {
            mActivityManager = new ActivityManager();
        }
        return mActivityManager;
    }

    /**
     * 将Activity添加到栈中
     */
    public void addActivity(Activity activity) {
        if (debug)
            Log.d(TAG, "addActivity!");

        if (activityStack == null) {
            activityStack = new Stack<Activity>();
        }

        activityStack.add(activity);
    }

    /**
     * 获得当前栈顶的Activity
     */
    public Activity getCurrentActivity() {
        if (debug)
            Log.d(TAG, "getCurrentActivity!");

        Activity activity = null;
        if (activityStack != null && !activityStack.isEmpty()) {
            activity = activityStack.lastElement();
        }
        return activity;
    }

    /**
     * 将Activity从栈中移除
     */
    public void removeActivity(Activity activity) {
        if (debug)
            Log.d(TAG, "removeActivity!  " + activity.getLocalClassName());

        if (activityStack != null && activityStack.size() > 0) {
            activityStack.remove(activity);
            activity.finish();
        }
    }

    /**
     *
     */
    public boolean hasForegroundActivies(){
        return activityStack.size() != 0;
    }

    /**
     * 依次移除栈中的所有activity，用于退出应用时
     */
    public void removeAllActivity() {
        if (debug)
            Log.d(TAG, "removeAllActivity!");
        if (activityStack != null) {
            while (activityStack.size() > 0) {
                Activity activity = getCurrentActivity();

                if (activity == null)
                    break;

                removeActivity(activity);
            }
        }

    }
}
